package br.ucb.sigplan.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.ucb.sigplan.beans.Login;

public class Filtro implements Filter{
	
	private List<String> acoesPublicas;
	
	@Override
	public void destroy() {
	
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		Login login = (Login) session.getAttribute("login");
		
		String uri = req.getRequestURI();
		String acao = uri.substring(uri.lastIndexOf("/")+1);
		
		if (login == null && !getAcoesPublicas().contains(acao)) {
			
			resp.sendRedirect(req.getContextPath() +"/login.jsp");
			
		}else {
			chain.doFilter(request, response);
			
		}
		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		setAcoesPublicas(new ArrayList<String>());
		String [] publicas = config.getInitParameter("public").split(",");
		for (String acao : publicas) 
		{
			getAcoesPublicas().add(acao);
		}
	
	}

	public List<String> getAcoesPublicas() {
		return acoesPublicas;
	}

	public void setAcoesPublicas(List<String> acoesPublicas) {
		this.acoesPublicas = acoesPublicas;
	}
	
	
}
